<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ArrowLeft } from '@element-plus/icons-vue'
import { getCarDetail, updateCar } from '@/api/car'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'

const router = useRouter()
const route = useRoute()
const formRef = ref(null)
const loading = ref(false)
// 文件列表（与表单数据分离，仅用于上传组件展示）
const fileList = ref([])
// 存储上传成功的图片地址（用于提交表单）
let imageUrl = ''

// 判断是否是编辑模式
const isEditMode = ref(route.params.id !== undefined)
// 表单数据
const form = reactive({
  id: route.params.id,
  licensePlate: '',
  brand: '',
  model: '',
  typeId: null,
  color: '',
  dailyRent: 0,
  images: '', // 存储图片地址，提交时赋值
  status: 0,
})
// 图片上传核心方法（与你的正确案例保持一致）
const get_image = async (uploadParams) => {
  try {
    // 从上传参数中获取文件对象
    const file = uploadParams.file
    const formData = new FormData()
    formData.append('file', file)

    const response = await axios.post('/api/file/upload1.do', formData)
    console.log('上传成功', response.data)

    form.images=response.data.message
    console.log(form.images)
    // 调用组件内置的成功回调（必须调用，否则组件会一直显示上传中）
    uploadParams.onSuccess(response.data.message)
    // 暂存图片地址
    imageUrl = response.data.data || response.data.message
    return response.data
  } catch (error) {
    console.error('上传失败', error)
    uploadParams.onError(error)
    ElMessage.error('上传失败，请重试')
    throw error
  }
}

// 预览图片
const handleImagePreview = (uploadFile) => {
  window.open(uploadFile.url, '_blank')
}

// 删除图片
const handleImageRemove = () => {
  imageUrl = ''
  fileList.value = []
}

// 上传前校验
const beforeImageUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  if (!isImage) {
    ElMessage.error('只能上传图片格式')
  }
  const isLt5M = file.size / 1024 / 1024 < 5
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过5MB')
  }
  return isImage && isLt5M
}

// 上传成功后的处理（同步更新文件列表和表单数据）
const handleUploadSuccess = (response, file, fileList) => {
  // 构建图片预览地址（使用后端返回的文件名）
  const filename = response.data || response.message
  const url = `/api/file/download.do?filename=${encodeURIComponent(filename)}`

  // 更新文件列表（用于组件展示）
  fileList.value = fileList.map(item => ({
    ...item,
    url: url // 补充完整预览地址
  }))

  // 更新图片地址（用于表单提交）
  imageUrl = filename
  ElMessage.success('图片上传成功')
}



// 表单验证规则
const rules = {
  licensePlate: [
    { required: true, message: '请输入车牌号', trigger: 'blur' }
  ],
  brand: [
    { required: true, message: '请输入品牌', trigger: 'blur' }
  ],
  model: [
    { required: true, message: '请输入型号', trigger: 'blur' }
  ],
  typeId: [
    { required: true, message: '请选择类型', trigger: 'change' }
  ],
  dailyRent: [
    { required: true, message: '请输入日租金', trigger: 'blur' },
    { type: 'number', message: '日租金必须是数字', trigger: 'blur' }
  ]
}

// 获取车辆详情（编辑模式）
const fetchCarDetail = async () => {
  try {
    loading.value = true
    const carId = Number(route.params.id)
    if (isNaN(carId)) {
      ElMessage.error('无效的车辆ID')
      return
    }

    const res = await getCarDetail(carId)
    if (res?.code === 200 && res.data) {
      Object.assign(form, res.data)

      // 回显图片（与上传逻辑保持一致）
      if (form.images) {
        imageUrl = form.images
        fileList.value = [{
          name: form.images,
          url: `/api/file/download.do?filename=${encodeURIComponent(form.images)}`
        }]
      }
    } else {
      ElMessage.error(res?.message || '获取车辆信息失败')
    }
  } catch (error) {
    console.error('获取车辆信息错误:', error)
    ElMessage.error('获取车辆信息失败')
  } finally {
    loading.value = false
  }
}

// 保存车辆信息
const handleSave = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    loading.value = true

    // 同步图片地址到表单
    // form.images = imageUrl
console.log(form.images)
    // 处理id格式（新增时为null，编辑时为数字）
    const payload = {
      ...form,
      id: isEditMode.value ? Number(form.id) : null
    }

    const res = await updateCar(payload)
    if (res?.code === 200) {
      ElMessage.success('保存成功')
      await router.push('/vehicle-query')
    } else {
      ElMessage.error(res?.message || '保存失败')
    }
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    loading.value = false
  }
}

// 返回
const goBack = () => {
  router.back()
}

// 初始化
onMounted(() => {
  if (isEditMode.value) {
    fetchCarDetail()
  }
})
</script>

<template>
  <div class="vehicle-edit-container">
    <div class="header-section">
      <el-button text size="small" @click="goBack" class="back-button">
        <el-icon><ArrowLeft /></el-icon> 返回
      </el-button>
      <h3 class="page-title">{{ isEditMode ? '编辑车辆' : '新增车辆' }}</h3>
    </div>

    <!-- 表单部分 -->
    <div class="form-section">
      <el-form
          :model="form"
          :rules="rules"
          ref="formRef"
          label-width="120px"
          class="vehicle-form"
          size="small"
      >
        <!-- 基础信息（与之前保持一致） -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="车牌号" prop="licensePlate">
              <el-input v-model="form.licensePlate" placeholder="请输入车牌号" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="品牌" prop="brand">
              <el-input v-model="form.brand" placeholder="请输入品牌" clearable />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="型号" prop="model">
              <el-input v-model="form.model" placeholder="请输入型号" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="车辆类型" prop="typeId">
              <el-select v-model="form.typeId" placeholder="请选择类型">
                <el-option label="轿车" :value="1" />
                <el-option label="SUV" :value="2" />
                <el-option label="跑车" :value="3" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="车辆颜色" prop="color">
              <el-input v-model="form.color" placeholder="请输入颜色" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="日租金(元)" prop="dailyRent">
              <el-input-number v-model="form.dailyRent" :min="0" :step="0.01" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 图片上传（关键修改部分） -->
        <el-form-item label="车辆图片" prop="images">
          <el-upload
              :http-request="get_image"
              list-type="picture-card"
              :file-list="fileList"
              :on-preview="handleImagePreview"
              :on-remove="handleImageRemove"
              :before-upload="beforeImageUpload"
              :on-success="handleUploadSuccess"
              :on-error="handleUploadError"
              :limit="1"
              :on-exceed="() => ElMessage.warning('只能上传一张图片')"
              accept="image/*"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
        </el-form-item>

        <!-- 车辆状态 -->
        <el-form-item label="车辆状态">
          <el-radio-group v-model="form.status">
            <el-radio :label="0">可租</el-radio>
            <el-radio :label="1">已租</el-radio>
            <el-radio :label="2">维修</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <!-- 操作按钮 -->
      <div class="action-section">
        <el-button size="small" @click="goBack">取消</el-button>
        <el-button
            size="small"
            type="primary"
            :loading="loading"
            @click="handleSave"
        >
          保存
        </el-button>
      </div>
    </div>
  </div>


</template>

<style scoped>
/* 样式保持不变 */
.vehicle-edit-container {
  padding: 24px;
  height: 80vh;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  background-color: #f5f7fa;
}

.header-section {
  display: flex;
  align-items: center;
  margin-bottom: 24px;
}

.back-button {
  padding: 0;
  margin-right: 16px;
  font-size: 14px;
  color: #606266;
  transition: color 0.3s;
}

.back-button:hover {
  color: #409EFF;
}

.page-title {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: #303133;
}

.form-section {
  flex: 1;
  overflow: auto;
  background-color: #fff;
  padding: 24px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.vehicle-form :deep(.el-form-item) {
  margin-bottom: 24px;
}

.vehicle-form :deep(.el-form-item__label) {
  font-weight: 500;
  color: #606266;
}

.vehicle-form :deep(.el-input__inner),
.vehicle-form :deep(.el-select__input),
.vehicle-form :deep(.el-input-number__input) {
  border-radius: 4px;
  height: 36px;
  line-height: 36px;
}

.vehicle-form :deep(.el-input-number) {
  width: 100%;
}

:deep(.el-upload--picture-card) {
  width: 120px;
  height: 120px;
  line-height: 120px;
  margin-right: 16px;
  border-radius: 4px;
}

:deep(.el-upload-list__item) {
  width: 120px;
  height: 120px;
  margin-right: 16px;
  border-radius: 4px;
}

:deep(.el-radio-group) {
  display: flex;
  gap: 20px;
}

:deep(.el-radio) {
  font-size: 14px;
}

.action-section {
  margin-top: 24px;
  text-align: right;
}

.action-section {
  display: flex;
  justify-content: center;    /* 水平居中 */
  align-items: center;        /* 垂直居中 */
  margin-top: 20px;           /* 增加与上方内容的间距 */
  gap: 16px;                  /* 按钮之间的间距 */
}

.action-section :deep(.el-button--primary) {
  background-color: #409EFF;
  border-color: #409EFF;
}

.action-section :deep(.el-button--primary):hover {
  background-color: #66b1ff;
  border-color: #66b1ff;
}

::-webkit-scrollbar {
  width: 8px;
  height: 8px;
}

::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 4px;
}

::-webkit-scrollbar-thumb {
  background: #c0c4cc;
  border-radius: 4px;
}

::-webkit-scrollbar-thumb:hover {
  background: #909399;
}
</style>